import { Injectable } from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto'
import { promises as fsPromises } from 'fs'
import * as path from 'path'
import * as dayjs from 'dayjs';
import { ConfigureService } from '@app/configure';
const OSS = require('ali-oss');

@Injectable()
export class UploadService {
    constructor(
        private readonly config:ConfigureService
    ){}

    oss(){
        const alicloud = this.config.get('alicloud')
        return new OSS({
            region: alicloud.regionId,
            accessKeyId: alicloud.accessKeyId,
            accessKeySecret: alicloud.accessKeySecret
        });
    }

    delFiles(files:string[]) {
        files.forEach(file => {
            this.delFile(file)
        })
    }

    delFile(file:string) {
        try {
            return fsPromises.unlink(path.join(this.config.get('upload.dist'), file))
        } catch (error) {
            
        }
    }

    put(file:Express.Multer.File, flag?:string|number) : Promise<string>;
    put(file:Express.Multer.File[], flag?:string|number) : Promise<Array<string>>;

    async put(file:Express.Multer.File | Express.Multer.File[], flag?:string|number) :Promise<string|Array<string>>{
        // const bucket = this.config.get('alicloud.bucket')
        // console.log(bucket)
        // const oss = this.oss()
        // try {
        //     // 指定存储空间名称。
        //     const result = await oss.getBucketInfo(bucket)
        //     console.log('bucketInfo: ', result)
        // } catch (error) {
        //     console.log(error.name)
        //     // 判断指定的存储空间是否存在。
        //     if (error.name === 'NoSuchBucketError') {
        //         console.log('Bucket does not exist');
        //     }
        // }

        // return
        
        const date = dayjs()
        let uuid:string = randomUUID()

        const uploadDist = this.config.get('upload.dist')
        const subDir = path.join(String(date.year()), date.format('MMDD'))
        


        if(flag) {
            uuid = uuid + '&' + flag
        }

        await fsPromises.mkdir(path.resolve(uploadDist, subDir), {recursive : true})


        if(Array.isArray(file)) { //多文件上传
            const fileNames:string[] = []
            for(let i = 0; i < file.length; i ++) {
                const fileName = path.join(subDir, createHash('md5').update(uuid + '&' + file[i].originalname).digest('hex').toLowerCase() + path.extname(file[i].originalname))
                
                fsPromises.writeFile(path.resolve(uploadDist, fileName), file[i].buffer)
                
                fileNames.push(fileName)
                
            }

            return fileNames
        }else {
            const fileName = path.join(subDir, createHash('md5').update(uuid + '&' + file.originalname).digest('hex').toLowerCase() + path.extname(file.originalname))
            fsPromises.writeFile(path.resolve(uploadDist, fileName), file.buffer)
            return fileName
        }

    }
}
